package com.hiof.servercommunication.background.job;

import com.hiof.location.GpsMangerFactory;
import com.hiof.servercommunication.RestFulServiceManager;
import com.hiof.servercommunication.exception.NetworkException;
import com.hiof.servercommunication.exception.ServerException;
import com.hiof.servercommunication.push.beans.MediaSendPacket;
import com.hiof.servercommunication.receive.beans.AcknowledgePacket;
import com.hiof.servercommunication.receive.beans.GeoPoint;
import com.hiof.servercommunication.receive.beans.Packet;
import com.hiof.settings.user.TypeOfAttendant;
import com.hiof.settings.user.UserConfiguration;
import com.hiof.utility.Utility;

/**
 * Created with IntelliJ IDEA.
 * User: manish
 * Date: 4/16/12
 * Time: 3:02 PM
 * To change this template use File | Settings | File Templates.
 */
public class MediaSendJob extends AbstractJob {
    @Override
    protected Packet connect2Server() throws ServerException, NetworkException {
        MediaSendPacket packet = (MediaSendPacket) getSendData();
        int userId = UserConfiguration.getInstance().getUserId();
        int attendantCode = UserConfiguration.getInstance().getAttendantId();
        AcknowledgePacket acknowledgePacket = new AcknowledgePacket("ok");
        GeoPoint geoPoint = GpsMangerFactory.getGpsManager().getLatestLocation();
        if(geoPoint == null)
            geoPoint = new GeoPoint();
        try {
            if (UserConfiguration.getInstance().getTypeOfAttendant() == TypeOfAttendant.ATHLETE) {
                RestFulServiceManager.getInstance().sendAthletePictureMedia(userId, attendantCode, geoPoint.getLat(), geoPoint.getLng(), geoPoint.getAltitude(), packet);
            } else if (UserConfiguration.getInstance().getTypeOfAttendant() == TypeOfAttendant.SUPPORT) {
                RestFulServiceManager.getInstance().sendAthletePictureMedia(userId, attendantCode,  geoPoint.getLat(), geoPoint.getLng(), geoPoint.getAltitude(), packet);
            }
        } catch (NetworkException e) {
            Utility.error(this.getClass().toString(), "NetworkException when sending Live Location:" + e.getMessage());
            acknowledgePacket.setMessage("Network Error");
        } catch (ServerException e) {
            acknowledgePacket.setMessage("Server Error");
            Utility.error(this.getClass().toString(), "ServerException when sending Live Location:" + e.getMessage());
        }
        return acknowledgePacket;
    }

    public MediaSendJob(Packet sendData) {
        super(sendData);
    }
}
